<template>
<div id="app">
    <el-header>
        <!-- 定义对外部通讯的prop参数 -->
        <HeaderPage :avatar="avatar" :nick_name="nick_name" :is_admin="isAdmin"></HeaderPage>
    </el-header>
    
    <span class="page_title">{{page_title}}</span>
    <div class="group_panel">
        <el-card class="base_info">
            <el-row>
                <el-col span="4"><img ref="base_info_img"
                    :src="avatar" 
                    class="avatar"/>
                </el-col>
    
                <el-col span="4">
                    <div class="nick_name">{{ nick_name }}</div>
                </el-col>
                
                <el-col span="16">
                    <el-button  plain class="edit_button" @click="edit_panel=true">{{edit_button_name}}</el-button>
                </el-col>    
            </el-row>
        </el-card>
        
        <el-card class="base_info">
            <span style="font-size:0.85em;padding-left:1dvw;font-weight:500">我的推荐码</span>
            <span class="promotion_code"> {{promotion_code}}</span>
            <el-button plain style="margin-left:65dvw" @click="copy_promotion_link">点击复制推广链接</el-button>
        </el-card>

            <div class="my_property_collapse">
                <el-collapse v-model="my_property" @change="handleChange" accordion>
                  <el-collapse-item title="我的钱包" name="1">
                    <div>
                     我的余额:<span class="balance">{{formattedBalance}}</span>
                     <el-button class="charge_button" type="primary" plain @click="charge_panel=true">充值</el-button>
                    </div>
                    <div><el-button class="coupon_button" @click="goto_my_coupon">我的优惠券</el-button>
                    </div>
                    <div><el-button class="coupon_button" @click="goto_my_bill">我的账单</el-button>
                    </div>
                    
                    <div>提现</div>
                  </el-collapse-item>
                <el-collapse-item title="我的内容" name="2">
                    <el-button class="coupon_button"  @click="publish_words=true">发表内容</el-button>
                 

                    <div><el-button class="coupon_button" @click="goto_my_contribution">我贡献的内容</el-button></div>
                    <div><el-button class="coupon_button" @click="goto_my_favor">我收藏的内容</el-button></div>
                    <div>我认领的内容  暂缓开通</div>
                </el-collapse-item>
                   
                  <el-collapse-item title="我的课程" name="4">
                    <div>
                      <div>直播课</div>
                      <div>视频课</div>
                    </div>
                  </el-collapse-item>
                </el-collapse>
              </div>

        <el-drawer v-model="edit_panel" :direction="pop_direction">
            <template #header>
              <h4>{{edit_panel_title}}</h4>
            </template>
            <template #default>
              <div>
                
                <el-upload
                class="avatar-uploader"
                action="http://127.0.0.1:8000/upload/"
                :data="{path:'user_avatars/'}"
                :before-upload="beforeAvatarUpload"
                :ref="avater_uploader"
                :show-file-list="false"
                :on-success="avatarUploadSuccess"
                >
                <img v-if="avatar" ref="edit_panel_img" :src="avatar" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">上传图片</el-icon>
                点击头像更换图片
              </el-upload>

                <el-input v-model="nick_name" placeholder="输入用户名"
                @focus="nick_name_focus"
                @blur="nick_name_blur"></el-input>
                  <span class="is-error" v-if="nick_name_error && nick_name_active">只包含数字、字母和中文的2~32个字符</span> 
              </div>
            </template>
            <template #footer>
              <div style="flex: auto">
                <el-button @click="edit_panel=false">取消</el-button>
                <el-button type="primary" @click="update_profiles">确定</el-button>
              </div>
            </template>
          </el-drawer>


          <el-drawer v-model="charge_panel" :direction="pop_direction">
            <template #header>
              <h4>{{charge_panel_titel}}</h4>
            </template>
            <template #default>
              <div>
                <el-row>
                    <el-col :span="10" :offset="1" v-for="item in recharge_level">
                        <el-card class="price_tag" 
                        :class="{selected:isSelected(item)}"
                        @click="select_price(item)">
                            {{ item }} 元
                        </el-card>
                    </el-col> 
                </el-row>
              </div>
            </template>
            <template #footer>
              <div style="flex: auto">
                <el-button @click="cancel_recharge">取消</el-button>
                <el-button type="primary" ref="charge_btn" :disabled="recharge_amount==0" @click="recharging">确定</el-button>
              </div>
            </template>
          </el-drawer>


          <el-drawer v-model="publish_words" :direction="pop_direction">
            <template #header>
              <h4>发表内容</h4>
            </template>
            <template #default>
              <div>
                <el-row>
                    <div class="text_example">输入贴近生活的口语表达可以提高内容被访问的几率。</div>
                    <div class="text_example">例句</div>
                    <div class="text_example">普通话关键词：撸串</div>
                    <div class="text_example">中文普通话表达：今天晚上咱们去<b>撸串</b>吧</div>
                    <div class="text_example">目标语言表达：Let's go grill some skewers tonight!</div>
                    <div class="tag">标签：英语，生活口语</div>
                    <el-input class="context_input" v-model="mandarin_key_words" placeholder="输入中文普通话关键词"/>
                   <el-input
                        class="context_input" 
                        v-model="mandarin"
                        :rows="2"
                        type="textarea"
                        placeholder="上传中文普通话表达"
                    />
                   <el-input
                        class="context_input" 
                        v-model="target_language"
                        :rows="2"
                        type="textarea"
                        placeholder="上传对应语言表达"
                    />
                    <div  class="text_example">选择读音方式</div>
                    <el-radio-group v-model="phonation_method">
                        <el-radio :disabled="true" :label="3">AI智能读音(暂不支持)</el-radio>

                            <el-radio-group class="voice_style" v-if="phonation_method==3" v-model="phonation_role">
                                <el-radio :label="3">磁性男嗓</el-radio>
                                <el-radio :label="6">优美女声</el-radio>
                            </el-radio-group>
                        <el-radio :label="6">上传本人读音</el-radio>
                    </el-radio-group>


                    <el-upload v-if="phonation_method==6"
                        :before-upload="beforePronuncationUpload"
                        :on-preview="handlePreview"
                        :on-remove="handleRemove"
                        :on-success="PronuncationUploadSuccess"
                        action="http://127.0.0.1:8000/upload/"
                        :data="{path:'prononunce/'}"
                    >
                        <span class="tip">只能上传.mp3或.wav文件，文件体积小于2MB。</span>    
                        <el-button v-if="phonation_method==6" type="primary">上传音频</el-button>
                    
                    </el-upload>
                
                <div>选择目标语言的特色标签：</div>
                <el-check-tag 
                    v-for="item in content_tags"
                    :key="item.key"
                    
                    class="mx-1"
                    effect="light"
                    :checked="tag_checked[item.key]"
                    @change="tags_changed(item.key)"
                >
                {{ item.label }}
                </el-check-tag>
                </el-row>
              </div>
            </template>
            <template #footer>
              <div style="flex: auto">
                <el-button @click="cancel_post_content">取消</el-button>
                <el-button type="primary" ref="post_content_btn" 
                :disabled="mandarin_key_words==null || mandarin==null || target_language==null || selected_tags.length===0" 
                @click="post_content">确定</el-button>
              </div>
            </template>
          </el-drawer>

    </div>
    <div>个人主页</div>
    <el-button plain type="primary" class="back_home" @click="back_home">返回首页</el-button>
    <FooterPage style="margin:40dvh 40dvw "></FooterPage>
</div>
 </template>
 
 <script>
 import HeaderPage from '@/components/HeaderPage.vue'
 import FooterPage from '@/components/FooterPage.vue'
 import { ElNotification } from 'element-plus';
 import { ref, watch } from 'vue';
 import axios from 'axios';
 import config from '../../spoken.config.json';
 import { ElMessage, ElMessageBox } from 'element-plus';

 export default{
     name:'UserCenter',
     components:{
        HeaderPage,
        FooterPage,
    },
   
     data(){
         return{
             userData:{},
             promotion_code:null,
             nick_name:null,
             avatar:null,
             user_id:null,
             page_title:'个人中心',
             edit_button_name:'编辑',
             edit_panel:false,
             publish_words:false,
             charge_panel:false,
             pop_direction:ref('rtl'),//抽屉弹出方向右向左
             edit_panel_title:'修改个人信息',
             charge_panel_titel:'充值',
             nick_name_active:false,
             nick_name_regex:/^^(?=.*[\u4e00-\u9fa5a-zA-Z\d])[\u4e00-\u9fa5a-zA-Z\d]{1,32}$/, //长度不超过32位的字符串，且只包含数字、字母和中文字符，可以使用以下正则表达式
             cash_balance:'- -',
             recharge_level:[10,30,50,100,200,500], // 充值档位
             recharge_amount:0,
             selected_card:null,
             phonation_method:null,
             phonation_role:null,
             mandarin_key_words:null, 
             mandarin:null,
             target_language:null,
             content_tags:config.CONTENT_TAGS,
             pronuncation_url:null,
             selected_tags:[],
             tag_checked:[],
             isAdmin:false,
            };
     },
     created(){
        this.user_profiles();
     },
    
     mounted(){
        console.log("mounted时候的user_id： "+this.user_id)
     },
     watch:{
        //监听数据变化
        userData:{
            //数据变化的时候会自动调用handler函数，并自动填充newData参数
            handler(newData){
                this.nick_name=newData.nick_name;
                this.avatar=newData.avatar;
            },
            deep:true, // 深度监听对象内部属性的变化
        },
     },

     computed:{
        nick_name_error(){
            return !this.nick_name_regex.test(this.nick_name);
        },
        formattedBalance(){
            return Number(this.cash_balance).toFixed(2)
        }
     },
     methods:{
        //折叠卡片被点击
       async handleChange(activeNames){
            console.log(activeNames)
            if(activeNames=="1"){
                //查询现金余额数据
                const data={'user_id':this.user_id};
                const res= await this.$commonFunctions.get_cash_balance(data);
                console.log("用户中心，查看我的钱包res："+JSON.stringify(res))
                if(res.code==20000){
                    this.cash_balance=res.data.balance;
                }else{
                    this.cash_balance='NaN';
                    ElNotification({
                        message: res.msg,
                        title: "系统消息",
                        type: "info",
                        duration: 3000,
                    }); 
                }
               
            }else if(activeNames=="2"){
               
            }else if(activeNames=="3"){
               
            }
        },
        //页面初始化
        async user_profiles(){
            //读cookie，获取用户token
            const login_token= this.$commonFunctions.get_cookies('login_token')
            console.log("用户中心初始化数据。login_token："+login_token);
            if(login_token!=null){
                const user_profiles= await this.$commonFunctions.get_user_profiles(login_token);
            //console.log("用户中心初始化数据。user_profiles："+user_profiles.nickname+" 头像地址："+user_profiles.avatar);
            
            //更新userData数据，触发watch的钩子
            this.userData.nick_name=user_profiles.name;
            this.userData.avatar=user_profiles.avatar;
            this.user_id=user_profiles.user_id;
            this.isAdmin=user_profiles.is_superuser
            
            console.log("用户中心初始化数据。user_id： "+this.user_id+" 下一步获取推荐码");
            //const rcode= await this.get_promotion_code();
            const rcode=await this.$commonFunctions.get_promotion_code(this.user_id)
            console.log("获取推荐码接口的返回值： "+JSON.stringify(rcode));
            this.promotion_code=rcode.promotion_code;
            //this.promotion_code=rcode.promotion_code;
                    
            // this.nick_name=user_profiles.name
            // this.avatar=user_profiles.avatar
            // this.user_id=user_profiles.user_id
            }else{
                ElNotification({
                        message: "您太长时间没有动作，为保证安全请重新登录",
                        title: "系统消息",
                        type: "info",
                        duration: 3000,
                    });
                    this.$router.push("/");
            }
            
        },

        //更改用户名和密码
        async update_profiles(){
            //检查数据有效性
            if(this.nick_name_regex.test(this.nick_name)){
                //调接口更新数据
                var data={}
                data['target']="user_profiles";
                data['id']=this.user_id;
                data['nick_name']=this.nick_name;
                data['avatar']=this.avatar;
                console.log("update_profiles函数调用更新前检查参数："+JSON.stringify(data));
                const update_profiles=await this.$commonFunctions.update_profiles(data);
                
                console.log("update_profiles函数的code获取返回结果："+update_profiles['code']);
                if(update_profiles['code']==20000){
                    //把cookie里存的就user_name和avatar都删掉，重新从接口请求
                    this.$commonFunctions.deleteCookie('user_name');
                    this.$commonFunctions.deleteCookie('avatar');
                    //调查询接口获取最新数据
                    this.user_profiles();
                    //返回正常关闭抽屉
                    this.edit_panel=false;
                }else{
                    ElNotification({
                        message: "用户信息更新失败，请检查后端接口",
                        title: "系统消息",
                        type: "info",
                        duration: 3000,
                    });
                }
            }
            else{
                ElNotification({
                message: "用户名只包含数字、字母和中文的2~32个字符",
                title: "系统消息",
                type: "info",
                duration: 3000,
                });
            } 
            //返回异常提示异常信息，不关闭抽屉
        },
        
        nick_name_focus(){
            this.nick_name_active=true;
        },
        nick_name_blur(){
            this.nick_name_active=false;
        },
        //上传头像成功
        avatarUploadSuccess(response){
            //上传完成后更新userData数据以触发watch的钩子
            this.userData.avatar=response.data[0]['url'];
            //this.new_avatar=response.data[0]['url'];
            console.log("上传成功的回调new_avater："+this.new_avatar);
        },
        //上传头像前的检查
        beforeAvatarUpload(rawFile){  
            // 实现上传前的逻辑
            console.log("执行上传动作前检查文件格式： "+rawFile.type)
            console.log("执行上传动作前检查文件体积："+rawFile.size)

            if (rawFile.type !== 'image/jpeg'&&rawFile.type !== 'image/png') {
                this.$message.error('只能上传png或jpg个格式的文件');
                return false;
            } else if (rawFile.size / 1024 / 1024 > 2) {
                this.$message.error('文件体积不能超过2MB');
                return false;
            }
            return true;
        },
        // 上传发音前检查
        beforePronuncationUpload(rawFile){  
            // 实现上传前的逻辑
            console.log("执行上传动作前检查文件格式： "+rawFile.type)
            console.log("执行上传动作前检查文件体积："+rawFile.size)

            if (rawFile.type !== 'audio/mpeg'&&rawFile.type !== 'audio/x-wav') {
                this.$message.error('只能上传mp3或wav个格式的文件');
                return false;
            } else if (rawFile.size / 1024 / 1024 > 2) {
                this.$message.error('文件体积不能超过2MB');
                return false;
            }
            return true;
        },
        // 上传发音成功的回调
        PronuncationUploadSuccess(response){
            //上传完成后更新userData数据以触发watch的钩子
            this.pronuncation_url=response.data[0]['url'];
            //this.new_avatar=response.data[0]['url'];
            console.log("上传成功的回调音频文件地址："+this.pronuncation_url);
        },
        handleRemove(file, uploadFiles){
            console.log(file, uploadFiles)
        },
        handlePreview (uploadFile){
            console.log(uploadFile)
        },
        tags_changed(key){
            console.log("tag开关："+key)
            if(this.tag_checked[key]==true){
                const swift_array=this.selected_tags.filter(value=>value!=key)
                this.selected_tags=swift_array
                this.tag_checked[key]=false
            }else{  
                this.selected_tags.push(key)
                this.tag_checked[key]=true
            }
            console.log("标签选择情况："+this.selected_tags+" ")
        },

        decode_tags(tags){
            const res=[];
            tags.forEach(element => {
                console.log(element)
              res.push(this.content_tags.find(obj=>obj.key===element).label);
            });
            return(res)
        },
        //保存数据
        async post_content(){
            try{
                console.log("开始发布内容流程……")

                this.$refs["post_content_btn"].disabled=true;
                const business_id=crypto.randomUUID().replace(/-/g,'');
                    const data={
                        "mandarin_key_words":this.mandarin_key_words,
                        "mandarin":this.mandarin,
                        "target_language":this.target_language,
                        "pronuncation_url":this.pronuncation_url,
                        "business_id":business_id,
                        "tags":this.decode_tags(this.selected_tags),
                        "uid":this.user_id,
                    };
                    await axios.post("/api/post_content/", data, { withCredentials: true })
                        .then(response => {
                        console.log(response.data)
                            if (response.data["code"] == 20000) {
                               
                                ElMessageBox.alert(
                                    response.data["msg"],
                                    "系统消息",
                                    {
                                        confirmButtonText:'知道了',
                                        callback:()=>{
                                            this.publish_words=false;
                                            this.phonation_method=null;
                                            this.phonation_role=null;
                                            this.mandarin_key_words=null; 
                                            this.mandarin=null;
                                            this.target_language=null;
                                            this.pronuncation_url=null;
                                            this.selected_tags=[];
                                            this.tag_checked=[];
                                        }
                                    }
                                ); 
                            }
                            else {
                                ElNotification({
                                    message:response.data["msg"],
                                    title: response.data["code"],
                                    type: "info",
                                    duration: 3000,
                                }); 
                            }
                        });  
                
            }catch(error){
                console.log(error)
            }
            finally{
                        this.$refs["post_content_btn"].disabled=false;
                        this.selected_tags=[]
                 }
        },
        //保存数据
        cancel_post_content(){
            this.publish_words=false;
            this.phonation_method=null;
            this.phonation_role=null;
            this.mandarin_key_words=null; 
            this.mandarin=null;
            this.target_language=null;
            this.pronuncation_url=null;
            this.selected_tags=[];
            this.tag_checked=[];
        },
        //返回首页
        back_home(){
            this.$router.push("/dictionary");
        },
    
        //复制推广链接
        copy_promotion_link(){
            navigator.clipboard.writeText(config.promotion_link+'?rcode='+this.promotion_code);
            ElNotification({
                        message: "推广链接已复制到剪贴板上",
                        title: "系统消息",
                        type: "info",
                        duration: 3000,
                    }); 
                },
        
        //跳转到优惠券页面
        goto_my_coupon(){
            console.log('即将跳转到优惠券页面')
            this.$router.push({name:'MyCoupon'});
        },

        //跳转到我贡献的内容页面
        goto_my_contribution(){
            console.log('即将跳转到我贡献的页面')
            this.$router.push({name:'MyContribution'});
        },

        //跳转到我收藏的内容页面
        goto_my_favor(){
            console.log('即将跳转到我收藏的页面')
            this.$router.push({name:'MyFavor'});
        },

        // 充值
        async recharging(){
        try{
                console.log("开始充值流程……"+this.recharge_amount)

                this.$refs["charge_btn"].disabled=true;

                if(this.recharge_amount!=0){
                    const uuid=crypto.randomUUID().replace(/-/g,'');
                    const data={
                        "user_id":this.user_id,
                        "amount":this.recharge_amount,
                        "order_id":uuid};
                    await axios.post("/api/wx_charge/", data, { withCredentials: true })
                        .then(response => {
                        console.log(response.data)
                            if (response.data["code"] == 20000) {
                                console.log("wx_pay_native接口返回的数据："+JSON.stringify(response.data["data"][0]))
                                const res=response.data["data"][0]
                                console.log("order_id: "+res.order_id)
                                console.log("amount: "+this.recharge_amount)
                                console.log("user_id: "+this.user_id)
                                console.log("qrcode: "+res.qrcode)
                                //this.cash_balance=res[0].balance
                                //跳转到支付的url页面，显示paycode
                                this.$router.push(
                                    {name:'wx_pay_url_qrcode',
                                    params:{
                                        order_id:res.order_id,
                                        amount:this.recharge_amount,
                                        user_id:this.user_id,
                                        qrcode:res.qrcode,}});
                            }
                            else {
                                ElNotification({
                                    message:response.data["msg"],
                                    title: response.data["code"],
                                    type: "info",
                                    duration: 3000,
                                }); 
                            }
                        });  
                }else{
                    ElNotification({
                                    message:"请选择充值金额",
                                    title: "充值提示",
                                    type: "warn",
                                    duration: 3000,
                                });  
                }
            }catch(error){
                console.log(error)
            }
            finally{
                this.$refs["charge_btn"].disabled=false;
            }
        },

        // 选择充值金额
        select_price(item){
            this.recharge_amount=item;
            console.log('当前选择的金额是：'+this.recharge_amount)
        },

        // 取消充值
        cancel_recharge(){
        this.charge_panel=false;
        this.recharge_amount=0},

        isSelected(item){
            return this.recharge_amount===item;
        },

         //跳转到账单页面
         goto_my_bill(){
            console.log('即将跳转到优惠券页面')
            this.$router.push({name:'mybill'});
        },

    },
}
                    
  
     
 </script>
 
 <style scoped>
 div#app{
    text-align: left;
 }
 .charge_button{
  float: right;
  margin-right: 5dvw;
 }
 .coupon_button{
    border: 0;
    padding-left: 0;
    font-size: var(--el-collapse-content-font-size);
    font-weight: bold;
 }
 .coupon_button:hover{
    background-color: transparent;
 }
 span.balance{
    margin-left: 2dvw;
 }
 .is-error{
    color:#dd2f18;
    font-size: 10pt;
 }
.promotion_code{
    margin-left:2dvw;
    color:blue;
    font-weight: 600;
    font-size: 14pt;
}
 .page_title{
     display:block; 
     font-weight: bold;
     font-size: 100%;
     letter-spacing: .25px;
     margin: 2dvh 2dvw;
     outline: 0;
     padding-bottom: 4px;
     padding-top: 8px;
 }
 .group_panel{
    border-radius: 10px; 
    box-shadow: 0px 0px 2px rgba(0, 0, 0, 0.24); 
 }
 .avatar{
    border-radius: 20px;
    width: 40px;
    height: 40px;
 }
img.avatar{
 margin-right: 20px;;    
}
div.avatar-uploader{
    margin-bottom: 20px;
}

 .nick_name{
    margin: 10px;
    font-weight: 400;
 }
 .edit_button{
    margin-top:5px ;
    margin-left: 67.5dvw;
 }
 .back_home{
    margin-top: 25dvh;
    margin-left: 30dvw;
    width: 40dvw;
 }
 div.my_property_collapse{
    padding-left: 2.5dvw;       
 }

 div.selected{
    border: 1px solid  #409eff;
    color: #409eff;
    font-weight: bold;
 }

 div{
    font-size: 12pt;
 }

.el-drawer__header{
    margin-bottom: 0px;
 }
 .text_example{
    color:#666;
    margin-bottom:12pt;
 }
 .context_input{
    margin: 12pt 0;
 }

 .voice_style{
    margin-left: 20px;
 }

 span.tip{
    color:#f06b0d;
    font-size: 10pt;
    font-weight: bold;
    display: block;
 }
 .mx-1{
    margin:0 2px;
 }
 </style>